package com.example.leetdemo.plan1;

import java.util.ArrayDeque;
import java.util.Queue;

public class Sword043 {

    public static class CBTInserter {

        Queue<TreeNode> queue;
        TreeNode root;

        public CBTInserter(TreeNode root) {
            this.root = root;
            queue = new ArrayDeque<>();
            queue.offer(root);
            while (queue.peek() != null && queue.peek().left != null && queue.peek().right != null) {
                TreeNode p = queue.peek();
                queue.offer(p.left);
                queue.offer(p.right);
                queue.poll();
            }
        }

        public int insert(int v) {
            TreeNode treeNode = new TreeNode();
            treeNode.val = v;
            TreeNode h = queue.peek();
            if (h.left == null) {
                h.left = treeNode;
            } else if (h.right == null) {
                h.right = treeNode;
                queue.offer(h.left);
                queue.offer(h.right);
                queue.poll();
            }
            return h.val;
        }

        public TreeNode get_root() {
            return root;
        }

    }

    public static class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
    }
}
